/*
 * Copyright (c) 2014 Luca Agostini, Alessandro Cantini, Alessandro Dignani
 *
 * This file is part of MeteoCal.
 *
 * MeteoCal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.polimi.se2.agostini_cantini_dignani.meteocal.gui;

import it.polimi.se2.agostini_cantini_dignani.meteocal.business.UserManager;
import it.polimi.se2.agostini_cantini_dignani.meteocal.util.FacesMessenger;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.ServletException;

@Named
@RequestScoped
public class LoginBean implements java.io.Serializable {

	private String email;
	private String password;

	@EJB
	private UserManager um;

	public String login() {
		FacesMessenger messenger = new FacesMessenger();

		if (um.findByEmail(email) == null) {
			messenger.add(email + " is not a registered email.", FacesMessage.SEVERITY_ERROR);
			return null;
		}

		FacesContext context = FacesContext.getCurrentInstance();
		try {
			um.login(context, email, password);
		} catch (ServletException e) {
			messenger.add("Login failed.", FacesMessage.SEVERITY_ERROR);
			return "index";
		}
		return "/user/home?faces-redirect=true";
	}

	public String logout() {
		return logout(true);
	}

	private String logout(boolean invalidateSession) {
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			um.logout(context, invalidateSession);
		} catch (ServletException e) {
			context.addMessage(null, new FacesMessage("Logout failed."));
		}

		return "/index?faces-redirect=true";
	}

	public String getEmail() {
		return this.email;
	}

	public void setEmail(String email) {
		this.email = email.trim();
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
